#!/usr/bin/env python
#coding=utf-8
#Simple HTTP Server With Upload.
#This module builds on BaseHTTPServer by implementing the standard GET
#and HEAD requests in a fairly straightforward manner.

import os
import sys
import time
import datetime
import getopt
import json
from socket import *
#from http.server import HTTPServer,BaseHTTPRequestHandler
from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler
import ssl
from BaseHTTPServer import BaseHTTPRequestHandler,HTTPServer

import io,shutil  
import urllib

curr_path = "./"

def isSubstr(s1,s2):
    return s1 in s2    
class Request(BaseHTTPRequestHandler):
    def do_POST(self):
        buf = "<html><body>This is a post() request!</body></html>\n"
        print
        print ("+++++[REQUEST]: head......");
        print ("POST %s" % self.path);
        print (self.headers);

        print ("+++++[REQUEST]: body......");
        length = int(self.headers.getheader('content-length'))
        qs = self.rfile.read(length)
        print (qs);

        # send response message
        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.send_header('Content-Length', len(buf))
        self.end_headers()
        print ("+++++[RESPONSE]: head......");

        print ("+++++[RESPONSE]: body......");
        self.wfile.write(buf) 
        print ("%s" % buf) 
        #resp_dict = {'key':'hello', 'password':'world'}
        #resp_str=json.dumps(resp_dict, sort_keys=False)
        #self.wfile.write(resp_str.encode())
        #resp_str = "PROCESSED SUCCESS"
        print ("+++++[RESPONSE]: END......")
        print

    def do_GET(self):
        print
        print ("+++++[REQUEST]: head......");
        print ("GET %s" % self.path);
        print (self.headers);

        print ("+++++[REQUEST]: body......");

        print ("+++++[RESPONSE]: head......");
        buf = "<html><body>This is a get() request!</body></html>\n"
        self.send_response(200)  
        enc = "UTF-8"
        self.send_header("Content-type", "text/html; charset=%s" % enc)  
        self.send_header("Content-Length", len(buf))  
        self.end_headers()  

        print ("+++++[RESPONSE]: body......");
        self.wfile.write(buf) 
        print ("%s" % buf) 
        #self.outputtxt(self.path)
        print ("+++++[RESPONSE]: END......");
     
    def outputtxt(self, content):
        enc = "UTF-8"
        content = content.encode(enc)
        f = io.BytesIO()
        f.write(content)
        f.seek(0)  
        self.send_response(200)  
        self.send_header("Content-type", "text/html; charset=%s" % enc)  
        self.send_header("Content-Length", str(len(content)))  
        self.end_headers()  
        shutil.copyfileobj(f,self.wfile)    
def run(Host, Port):
    host=Host
    port=Port
    #
    print('Listening on %s:%s' % (host,port))
    #server=HTTPServer((host,port),Request)
    server=HTTPServer((host, port), Request)
    server.socket = ssl.wrap_socket(server.socket, certfile='server.pem', server_side=True)

    #serve_forever
    server.serve_forever()

def init():
    if  not os.path.exists(curr_path):
        os.makedirs(curr_path)

if __name__=='__main__':
    opts, args = getopt.getopt(sys.argv[1:], "h:p:", ["host=", "port="])
    #print("[*] Params: ", opts)
    ParamHost = '127.0.0.1'
    ParamPort = 443
    for opt_name,opt_val in opts:
        if opt_name in ('-h', '--host'):
            ParamHost = opt_val
            print ("[*] Param: -h ", ParamHost)
        if opt_name in ('-p', '--port'):
            ParamPort = int(opt_val)
            print ("[*] Param: -p ", ParamPort)
            break
        # print(Request.path)
    init()
    #time.sleep(1)
    if ParamPort < 1:
        print ("[*]: input param error, no port is defined");
        sys.exit()
    run(ParamHost, ParamPort)
